import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
const bleManager = require('../../utils/BLE/CRBleManager.js')
const spo2Analyzer = require('../../utils/BLE/CRSpo2Analyze.js')
const tool = require('../../utils/FunctionTool.js')
const valuePlaceHolder = '~'

//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;
var seriesDataArrPr = [];
var timeArrPr = [];
var chartPr = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		showDialogdevice: false,
		searchType: 1,
		jgjd: [
			{ sorce: '95%-99%', result: '正常', desc: '没有明显的呼吸困难，可能呼吸会有点急促', bgc: '#e1f1e4', color: '#5ABA69' },
			{ sorce: '80%-95%', result: '轻度缺氧', desc: '没有明显的呼吸困难，可能呼吸会有点急促', bgc: '#fbf0d2', color: '#F1B100' },
			{ sorce: '80%-95%', result: '中度缺氧', desc: '意识还清醒，但口唇、甲床出现明显的发绀(青紫色)', bgc: '#fae0cd', color: '#FA6400' },
			{ sorce: '低于60%', result: '重度缺氧', desc: '会出现明显的意识障碍、嗜睡、昏迷、全身紫绀、严重的吸气性呼吸困难患者可能还会出现锁骨、胸骨、肋骨下陷的现象', bgc: '#f9dad6', color: '#FE3A32' }
		],
		wh: [
			{ desc: '血氧饱和度<90%，可能存在低血氧症，治疗以氧疗为主、纠正体内缺氧状态', bgc: '#fbf0d2', color: '#F7B500' },
			{ desc: '血氧饱和度<80%，可能存在生命危险', bgc: '#fae0cd', color: '#FA7400' },
			{ desc: '短期缺氧，血氧含量不低，可能影响较小', bgc: '#f9dad6', color: '#FE3A32' },
			{ desc: '长期缺氧会导致各个脏器功能障碍，可能出现"肾功能障碍、性功能障碍、肝功能异常、还有大脑功能障碍如乏力、意识障碍', bgc: '#ebcdcb', color: '#B10000' }
		],
		inputshow: false,
		inputlist: [
			{ unit: '%', value: '', text: '请输入血氧' },
			{ unit: '次/分', value: '', text: '请输入心率' },
			// { unit: 'bpm', value: '', text: '请输入脉率' },
			// { unit: '%', value: '', text: '请输入灌注指数' }
		],
		c_val: 80,
		shebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/xueya.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		hartValue: '',
		upValue: '',
		downValue: '',
		linedata: null,
		show: false,
		ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
		},
		linedatapr: null,
		showpr: false,
		ecpr: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chartPr = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chartPr);
				return chartPr;
			}
		},
		deviceList: [],
		isEnd: false,
		deviceConnectDeviceId: null,
		device: null,
		showDialog: false,
		bindDeviceTextInfo: '',
		spo2Value: null,
		showSpo2Value: '--',
		searchDevice: [],
		connected: false,
		available: true
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// this.drawProgress()
		this.gethistrorylist(); //查看历史数据
		this.getloadlist(); //查询当前最新数据
		const that = this
		//蓝牙管理
		// bleManager.setDelegate({
		// 	// BluetoothInitSuccessed: that.bluetoothInitSuccessed,
		// 	//蓝牙初始化失败
		// 	BluetoothInitFailed: that.bluetoothInitFailed,
		// 	//蓝牙状态改变
		// 	// GetBluetoothAdapterState: that.getBluetoothAdapterState
		// })
		setTimeout(() => {
			if (this.data.available) {
				this.get()
			}
		}, 1000)
	},
	gethistrorylist() {
		api
			.post('/api/exams/records', {
				data: {
					begindate: daysbefore.daysbefore(7),
					enddate: formatTime2(),
					everyday: true,
					itemcode: 'XYZBXY001004',
					typecode: 'bloodoxygen',
					everyday: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const valuepr = [];
					const times = [];
					const timespr = [];
					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001003" 的项
							// const item = device.items.find((item) => item.code === 'XYZBXY001004');
							// console.log(items);
							// 如果找到了，将 value 和 time 添加到相应的数组中
							device.items.forEach(subItem => {
								if (subItem.code === 'XYZBXY001004') {
									values.push(Number(subItem.value));
									times.push(entry.time.slice(5, 10).replace(/-/g, '/'));
								} else if (subItem.code === 'XYZBXY001005') {
									valuepr.push(Number(subItem.value));
									timespr.push(entry.time.slice(5, 10).replace(/-/g, '/'));
								}
							});
							// device.forEach(item => {
							// 	if (item.code === 'XYZBXY001004') {
							// 	  values.push(Number(item.value));
							// 	  times.push(entry.time.slice(5, 10).replace(/-/g, '/'));
							// 	} else if (item.code === 'XYZBXY001005') {
							// 	  valuepr.push(Number(item.value);
							// 	  timespr.push(entry.time.slice(5, 10).replace(/-/g, '/'));
							// 	}
							//   });
							// if (item) {
							// 	console.log(item);
							// 	values.push(Number(item.value)); // 将值转换为数字类型
							// 	times.push(entry.time.slice(5, 10).replace(/-/g, '/'));
							// }
						});
					});
					const linedata = {
						valuepr,
						values,
						times,
						timespr
					};
					console.log(linedata);
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
						this.getEchartDataPr(linedata);
					}, 1000);
				}
			});
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'bloodoxygen',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				this.setData({
					newtime: res[0].examtime
				});
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBXY001004') {
						this.setData({
							hartValue: Math.floor(parseInt(array[y].value))
						});
					}
					if (array[y].code == 'XYZBXY001005') {
						this.setData({
							prValue: Math.floor(parseInt(array[y].value))
						});
					}
					// if (array[y].code == 'XYZBXY001003') {
					// 	this.setData({
					// 		upValue: array[y].value
					// 	});
					// }
					// if (array[y].code == 'XYZBXY001002') {
					// 	this.setData({
					// 		downValue: array[y].value
					// 	});
					// }
				}
			});
	},
	savedevices() {
		console.log('2222');
		let data = {
			name: '血氧监测',
			time: formatTime(),
			typecode: 'bloodoxygen',
			typename: '血氧监测',
			devices: [
				{
					name: '血氧监测',
					kind: 'bloodoxygen',
					items: [
						{
							code: 'XYZBXY001004',
							checkDate: null,
							level: null,
							value: this.data.inputlist[0].value,
							deviceBrand: '',
							deviceNo: ''
						},
						{
							code: 'XYZBXY001005',
							checkDate: null,
							level: null,
							value: this.data.inputlist[1].value,
							deviceBrand: '',
							deviceNo: ''
						},
						// {
						// 	code: 'XYZBXY001003',
						// 	checkDate: null,
						// 	level: null,
						// 	value: this.data.inputlist[1].value,
						// 	deviceBrand: '',
						// 	deviceNo: ''
						// },
						// {
						// 	code: 'XYZBXY001002',
						// 	checkDate: null,
						// 	level: null,
						// 	value: this.data.inputlist[2].value,
						// 	deviceBrand: '',
						// 	deviceNo: ''
						// }
					]
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	userNameInput1(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[1].value': Math.floor(parseInt(e.detail.value))
		});
	},
	userNameInput3(e) {
		this.setData({
			'inputlist[2].value': e.detail.value
		});
	},
	saveNickname() {
		console.log(this.data.inputlist);
		this.savedevices();
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
	},
	// 绘制图表
	runColumncCanva() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: ['#37A2DA'],
			legend: {
				data: ['近一年血氧监测变化趋势'],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
					color: '#333333',
					fontSize: 13
				}
			},
			grid: {
				left: '0%',
				right: '5%',
				bottom: 0,
				top: '15%',
				containLabel: true,
				show: true
			},

			tooltip: {
				show: true,
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: timeArr,
				axisLabel: {
					fontSize: 16,
					rotate: 0 //倾斜度 -90 至 90 默认为0
				}
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: {
						type: 'dashed'
					}
				},
				axisLabel: {
					fontSize: 16
				}
			},
			series: seriesDataArr
		};
		//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
		if (chart) {
			chart.setOption(option);
			this.setData({
				show: true
			});
		}
	},
	getEchartData(linedata) {
		seriesDataArr = [
			{
				name: '近一年血氧监测变化趋势',
				type: 'line',
				stack: 'Total',
				smooth: true,
				data: linedata.values
			}
		];
		timeArr = linedata.times;
		this.runColumncCanva();
	},
	// 绘制图表
	runColumncCanvaPr() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: ['#37A2DA'],
			legend: {
				data: ['近一年心率监测变化趋势'],
				icon: 'circle',
				left: 0,
				itemWidth: 9,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
					color: '#333333',
					fontSize: 13
				}
			},
			grid: {
				left: '0%',
				right: '5%',
				bottom: 0,
				top: '15%',
				containLabel: true,
				show: true
			},

			tooltip: {
				show: true,
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: timeArrPr,
				axisLabel: {
					fontSize: 16,
					rotate: 0 //倾斜度 -90 至 90 默认为0
				}
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: {
						type: 'dashed'
					}
				},
				axisLabel: {
					fontSize: 16
				}
			},
			series: seriesDataArrPr
		};
		//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
		if (chartPr) {
			chartPr.setOption(option);
			this.setData({
				showpr: true
			});
		}
	},
	getEchartDataPr(linedata) {
		seriesDataArrPr = [
			{
				name: '近一年心率监测变化趋势',
				type: 'line',
				stack: 'Total',
				smooth: true,
				data: linedata.valuepr
			}
		];
		timeArrPr = linedata.timespr;
		this.runColumncCanvaPr();
	},
	doSearch(type) {
		this.setData({
			isEnd:false,
			searchType: type
		})
		console.log(this.data.searchType, 'searchType')
		this.setBleCallBack()
		this.setPODCallBack()
		setTimeout(() => {
			this.startSearch()
		}, 1500)
	},
	async get() {
		this.setData({
			bindDevice: []
		})
		try {
			this.setData({
				loading: true
			})
			const res = await api.post('/api/user/storage/get', {
				data: {
					'key': 'devicelist'
				}
			})
			console.log(res);
			if (res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'bloodoxygen')
				if (listValue.length > 0 && listValue[0].devicelist.length > 0) {
					this.setData({
						connected: true,
						device: listValue[0].devicelist[0]
					})
					this.doSearch(1)
				} else {
					console.log('不进来吗---111-----------');
					this.setData({
						connected: false,
						showDialogdevice: true
					})
				}
			} else {
				console.log('不进来吗---222-----------');
				this.setData({
					showDialogdevice: true
				})
			}
			this.setData({
				loading: false
			})
		} catch (e) {
			console.log('get->', e)
			return null
		}
	},
	// 链接设备
	goBindEq() {
		// this.setData({
		// 	bindDeviceTextInfo: '正在链接蓝牙设备测量中'
		// })
		// this.setData({
		// 	showDialog: true
		// })

		wx.navigateTo({
			url: '/bloodoxygen/pages/measurement/index'
		});
	},
	onCancel() {
		this.setData({
			showDialog: false,
		})
	},
	connectDevice(device) {
		console.log(device, 'device设备连接')
		this.setData({
			bindDeviceTextInfo: '正在链接蓝牙设备测量中'
		})
		this.setData({
			showDialog: true
		})
		// 正在连接设备
		bleManager.connectDevice(device)
	},
	getSearchDevice() {
		return this.data.searchDevice
	},
	searchComplete(devicesList) {
		console.log(devicesList, 'devicesListdevicesList')
		//根据名称筛选设备
		let fitDevices = []
		for (var i = 0; i < devicesList.length; i++) {
			let device = devicesList[i]
			if (device.name.indexOf("PC-60F") !== -1) {
				fitDevices[fitDevices.length] = device
			}
		}
		/** 根据设备的个数判断下一步*/
		//没有合适的设备，继续搜索
		if (fitDevices.length === 0 && !this.data.isEnd) {
			bleManager.startSearch(2)
			return
		}
		//只有一个设备，连它
		this.setData({
			searchDevice: fitDevices
		})
		if (this.data.searchType == 1) {
			this.connectDevice(fitDevices[0])
		} 
	},
	didConnectDevice(device) {
		// 连接成功

		// 保持屏幕常亮
		// setKeepScreenOn({
		//   keepScreenOn: true
		// })
		//更新设备名称
		// setDeviceInfo({name: device.name})
		this.setData({
			device: device
		})
		spo2Analyzer.didConnectDevice(device)
		spo2Analyzer.spo2WaveEnable(device, true)
		spo2Analyzer.spo2ParamEnable(device, true)
	},
	// 断开连接
	didDisconnectDevice(device) {
		console.log('断开连接')
		spo2Analyzer.willDisconnect(device)
		this.setData({
			device: null
		})
		// setDeviceInfo({name: nullDevIceName})
		// setShowDeviceInfo(false)
	},
	// 
	connectFailed(device) {
		console.log('连接失败')
		wx.showModal({
			title: '连接失败',
			content: '点击确定将重新开始连接',
			showCancel: false,
			cancelColor: '',
			confirmText: '确定',
			success: (res) => {
				this.startSearch()
			},
			fail: (res) => {
			},
			complete: (res) => {
			},
		})
	},
	bluetoothInitFailed() {
		this.setData({
			bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙',
			available: false
		})
		this.setData({
			showDialog: true
		})
	},
	getBluetoothAdapterState(state) {
		console.log(state)
		if (state.available === true) {
			// 蓝牙已打开
			console.log('蓝牙已打开,开始搜索')
			this.setData({
				available: true
			})
			return
		}
		this.setData({
			bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙',
			available: false
		})
		this.setData({
			showDialog: true
		})
	},
	bluetoothInitSuccessed() {
		console.log('bujinlaima-----------');
		this.setData({
			available: true
		})
	},
	startSearch() {
		if (!this.data.isEnd) {
			console.log('开始搜索')
			bleManager.startSearch()
		}
	},
	setBleCallBack() {
		const that = this
		//蓝牙管理
		bleManager.setDelegate({
			//搜索结束
			SearchComplete: that.searchComplete,
			//成功连接设备
			DidConnectDevice: that.didConnectDevice,
			//蓝牙已断开
			DidDisconnectDevice: that.didDisconnectDevice,
			//蓝牙连接失败
			ConnectFailed: that.connectFailed,
			//蓝牙初始化成功
			BluetoothInitSuccessed: that.bluetoothInitSuccessed,
			// //蓝牙初始化失败
			// BluetoothInitFailed: that.bluetoothInitFailed,
			//蓝牙状态改变
			GetBluetoothAdapterState: that.getBluetoothAdapterState
		})
	},
	setPODCallBack() {
		const that = this
		spo2Analyzer.setDelegate({
			//设备信息
			GetFourBitsDeviceInfo: that.getDeviceInfoWithSoftWareVersion,
			GetTwoBitsDeviceInfo: that.getDeviceInfoWithSoftWareVersion,
			GetDeviceBatteryLevel: that.getDeviceBatteryLevel,
			// GetSpo2Wave: that.getSpo2WaveDatas,
			GetSpo2Param: that.getSpo2ParamDatasWithSpo2Value,
			GetWorkStatusData: that.getPC60FWorkStatusData
		})
	},
	getDeviceInfoWithSoftWareVersion(softWareVersion, hardWareVersion, battaryLevel, chargingState, device) {
		// setDeviceInfo({
		//     name: device.name,
		//     softWare: softWareVersion,
		//     hardWare: hardWareVersion,
		//     level: battaryLevel
		// })
		// setDeviceInfo(showDeviceInfo)
	},
	getDeviceBatteryLevel(battaryLevel, device) {
		// setDeviceInfo({name: device.name, level: battaryLevel})
		// setShowDeviceInfo(true)
	},
	getSpo2WaveDatas(spo2Wave, length, device) {
		let canvasHeigth = spo2CanvasView.height
		var datas = []
		for (var i = 0; i < length; i++) {
			let beat = spo2Wave[i].pulse
			if (beat !== 0) doHeartBeat()
			datas[i] = (128 - spo2Wave[i].waveValue) / 128 * canvasHeigth
		}
		// drawTool.addPoints(spo2CanvasView, datas, 'red')
	},
	//获取血氧参数
	getSpo2ParamDatasWithSpo2Value(spo2Value, prValue, piValue, leadOff, mode, device) {
		//值过滤 血氧值不在此处理
		let prDisplay = tool.getValidValue(prValue, valuePlaceHolder)
		var piDisplay = tool.getValidValue(piValue * 0.1, valuePlaceHolder)
		if (piDisplay !== valuePlaceHolder) piDisplay = tool.keepFloatFomat(piDisplay, 1)
		// console.log(spo2Value === 0 ? -1 : spo2Value, 'spo2Value')
		console.log(prDisplay, 'prDisplay')
		// console.log(prDisplay, 'prDisplay')
		// console.log(piDisplay, 'piDisplay')
		this.setData({
			testSpo2Value: spo2Value,
			testPrValue: prDisplay
		})
		//最近一次记录隐藏
		// setSpo2Value(spo2Value === 0 ? -1 : spo2Value)
		// setPrValue(prDisplay)
		// setPiValue(piDisplay)
		// setLastSpo2ResultDataHidden(true)
		// //手指脱落,并且是在指甲血氧仪的情况下，重置。
		// setSpo2LeadOff(leadOff === 1)
		// if (leadOff === 1) {
		//     //显示手指脱落
		//     setResultStr(getResultString(20))

		//     // drawTool.setResult(spo2CanvasView, 20)
		//     // resetSpo2Data()
		// }
	},
	getPC60FWorkStatusData(mode, stage, para, otherPara, device) {
		console.log(mode, 'modemodemodemodemode')
		switch (mode) {
			case 1://普通测量模式
				this.workStateCommanMessure(stage, para, otherPara)
				break;
			case 2://连测模式
				this.workStateContiniousMessure(para, otherPara)
				break;
			case 3://菜单模式
				this.workStateMenuMode()
				break;
		}
	},
	workStateContiniousMessure(para, otherPara) {
		console.log(para, otherPara, 'otherParaotherParaotherPara')
		console.log(this.data.testSpo2Value, 'this.data.testSpo2Value')
		console.log(this.data.testPrValue, 'this.data.testPrValue')
	},
	workStateCommanMessure(stage, para, otherPara) {
		console.log(stage, 'stagestagestage')
		// setIsContinuousMode(false)
		switch (stage) {
			case 1://准备阶段
				// workStateCommanMessurePrepare()
				break;
			case 2://测量阶段
				// workStateCommanMessureing(para)
				break;
			case 3://播报结果
				// workStateCommanMessureBroadcasting(para, otherPara)
				break;
			case 4://脉率分析结果
				this.workStateCommanMessureComplete(para)
				break;
			case 5://测量完成
				// this.workStateCommanMessureComplete()
				break;
			default:
				break;
		}
	},
	workStateCommanMessureComplete() {
		this.setData({
			bindDeviceTextInfo: '测量成功'
		})
		setTimeout(() => {
			this.setData({
				showDialog: false
			})
		}, 500);
		this.setData({
			isEnd: true
		})
		this.setData({
			showSpo2Value: Math.floor(parseFloat(this.data.testSpo2Value)),
			testPrValue: this.data.testPrValue
		})
		this.setData({
			'inputlist[0].value': Math.floor(parseFloat(this.data.showSpo2Value)),
			'inputlist[1].value': Math.floor(parseFloat(this.data.testPrValue))
		})
		this.savedevices()
	},
	gohistorypage() {
		wx.navigateTo({
			url: `/bloodoxygen/pages/history/index`,
		})
	},
	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function () { },

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() { },

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() { },

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		bleManager.closeConnection(this.data.device)
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() { },

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() { },

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() { }
});
